package com.example.xyblog.Controller;

import com.example.xyblog.Common.*;
import com.example.xyblog.Model.Articleinfo;
import com.example.xyblog.Model.Userinfo;
import com.example.xyblog.Service.ArticleService;
import com.example.xyblog.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private ArticleService articleService;


    @RequestMapping("/reg")
    public Object reg(@RequestPart("jpgfile") MultipartFile files,
                      @RequestParam(value = "username",required = true) String username,
                      @RequestParam(value = "password",required = true) String password,
                      @RequestParam(value = "address",required = true) String address
                      ) throws IOException {
        System.out.println(username);
        System.out.println(address);
        System.out.println(password);
        if(!StringUtils.hasLength(username) && !StringUtils.hasLength(password) && !StringUtils.hasLength(address)){
            return AjaxRespons.fail(-1,"存在未填必填项");
        }
        String fileName = UUID.randomUUID().toString().replaceAll("-", "")+files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
        String filePath = "/Users/mamba24/Desktop/regImg/"+fileName;
        files.transferTo(new File(filePath));
        String en_password= SecuryUtil.encryption(password);
        int ret=userService.addUser(filePath,address,username,en_password);
        if(ret == 1){
            return AjaxRespons.success(ret);
        }else{
            return AjaxRespons.fail(-1,"请重新注册");
        }
    }


    @RequestMapping("/login")

    public Object login(String username, String password, String identifyCode, HttpServletRequest request){
        //从session中取出验证码
        HttpSession session=request.getSession(false);
        String sessionCode = (String)session.getAttribute("identifyCode");
        System.out.println(username);
        System.out.println(password);
        //这里方便测试就使用固定验证码
        if (identifyCode.equalsIgnoreCase("1234")){
            Userinfo chk=userService.loginChk(username);
            if(SecuryUtil.decryption(password,chk.getPassword())){
                //登陆成功，存一手session
                session.setAttribute(ConstantVariable.SESSION_KEY_VALUE,chk);
                return AjaxRespons.success(1);
            }else {
                return AjaxRespons.fail(200,-1,"请输入正确的账号或密码");
            }


        }else{
            System.out.println("验证码错误");
            return AjaxRespons.fail(200,-1,"验证码错误");
        }

    }

    /**
     * 给前端返回一个验证码图片
     * @return
     */
    @RequestMapping("/identifyImage")
    public void identifyImage(HttpServletResponse response, HttpServletRequest request){
        //创建随机验证码
        IdentyUtil utils = new IdentyUtil();
        String identifyCode = utils.getIdentifyCode();
        //session存入验证码
        HttpSession session= request.getSession(true);
        session.setAttribute("identifyCode", identifyCode);
        //根据验证码创建图片
        BufferedImage identifyImage = utils.getIdentifyImage(identifyCode);
        //回传给前端
        utils.responseIdentifyImg(identifyImage,response);

    }

    @RequestMapping("/photoUpload")
    public void uploadPhoto(HttpServletResponse response,HttpServletRequest request) throws IOException {
        PhotoUtil util=new PhotoUtil();
        HttpSession session=request.getSession(false);
        Userinfo userinfo= (Userinfo) session.getAttribute(ConstantVariable.SESSION_KEY_VALUE);
        String imgPath=userinfo.getPhoto();

        Image image = ImageIO.read(new FileInputStream(imgPath));
        util.responseImage(image,response);
    }

    /**
     * 通过文章id获取作者id再根据作者id拿到图片
     * @param request
     * @return
     */
//    @RequestMapping("/photoUploadByArt")
//    public void photoUploadByArt(HttpServletResponse response,HttpServletRequest request,Integer aid) throws IOException {
//        System.out.println(aid);
//        PhotoUtil util=new PhotoUtil();
//       //先通过aid获取文章信息，再从文章信息中拿出uid，再根据uid拿到作者信息
//        Articleinfo articleinfo=articleService.getBlog(aid);
//        Integer uid=articleinfo.getUid();
//        Userinfo userinfo=userService.getUser(uid);
//        String imgPath=userinfo.getPhoto();
//        Image image = ImageIO.read(new FileInputStream(imgPath));
//        util.responseImage(image,response);
//    }

   @RequestMapping("/changePhoto")
   public void changePhoto(HttpServletResponse response,HttpServletRequest request){

    }
    @RequestMapping("/getUserinfo")
    public Object getUserinfo(HttpServletRequest request){
        HttpSession session= request.getSession(false);
        Userinfo userinfo=(Userinfo) session.getAttribute(ConstantVariable.SESSION_KEY_VALUE);
        userinfo.setBcount(userService.countBlogs(userinfo.getId()).size());
        return userinfo;
    }

    /**
     * 获取当前文章作者的信息
     * @param aid
     * @return
     */
    @RequestMapping("/getAuthurInfo")
    public Object getAuthurInfo(Integer aid){
        if(aid == null){
            return AjaxRespons.fail(-1,"aid无");
        }
        Articleinfo articleinfo=articleService.getBlog(aid);
        Integer uid=articleinfo.getUid();
        Userinfo userinfo=userService.getUser(uid);
        userinfo.setBcount(userService.countBlogs(userinfo.getId()).size());
        return userinfo;
    }
}
